package com.css.sword.knowing.search.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.css.sword.knowing.search.IndexInput;
import com.css.sword.knowing.search.SearchInput;
import com.css.sword.knowing.search.exception.ArgException;
import com.css.sword.knowing.toolkit.properties.CssPropertiesTool;

public class SearchUtil {

    public static Properties getProperties() throws IOException {

        Properties p = CssPropertiesTool.load(SearchUtil.class.getClassLoader(), "searchserver.properties");
    
        return p;
    }

    public static List getAddress(Properties p) throws IOException {

        List aps = new ArrayList();
        String address = p.getProperty("serversaddress");

        if (address != null) {

            String[] addressPort = address.split(" ");
            for (int i = 0; i < addressPort.length; i++) {
                String[] apArray = addressPort[i].split(":");
                aps.add(apArray);
            }

        }

        return aps;
    }

    public static boolean empty(String input) {
        return input == null || "".equals(input);
    }

    public static void validateSI(SearchInput si) throws ArgException {
        if (empty(si.getIndexName())) {
            throw new ArgException("索引名不能为空");
        }
        /*
         * if(null ==si.getTypeNames() || empty(si.getTypeNames()[0])) { throw
         * new ArgException("索引类型不能为空"); }
         * 
         * if(si.getSearchFields()==null || si.getSearchFields().length<1) {
         * throw new ArgException("索引字段不能为空"); }
         */
        if(si.isUseSystemID())
	        if (empty(si.getSystemID())) {
	            throw new ArgException("系统标识不能为空");
	        }
        if (si.getReturnFields() != null) {
            for (String returnField : si.getReturnFields()) {
                if (empty(returnField)) {
                    throw new ArgException("返回字段不能为空");
                }
            }
        }
    }

    private static boolean hasEmpty(String[] inputs) {
        for (String input : inputs) {
            if (empty(input)) {
                return true;
            }
        }
        return false;
    }

    public static void validateII(IndexInput ii) throws ArgException {
        if (empty(ii.getIndexName())) {
            throw new ArgException("索引名不能为空");
        }

        if (empty(ii.getTypeName())) {
            throw new ArgException("索引类型不能为空");
        }
        if (empty(ii.getSystemID())) {
            throw new ArgException("系统标识不能为空");
        }
    }

}
